package com.sto.stoapp.activity.sales;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.adapter.SalesSignSelectSpninerAdapter;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.entity.BillPaymentEntity;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.HelpGetPaymentThread;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wj on 2016-12-05.
 */

public class SalesSignHelpActivity extends StoListenerActivity {

    private int title;
    /**
     * 签收人选择
     */
    private Spinner namesSpinner;
    private List<String> names=new ArrayList<String>();
    private String signName="";
    /**
     * 签收人电话
     */
    private EditText phoneET;
    private List<EditText> edit = new ArrayList<EditText>();
    /**
     * 单号扫描
     */

    private DataBusinessEntity dataBusiness;

    private SalesSignSelectSpninerAdapter adapter;

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what){
                case HelpGetPaymentThread.MSG_WHAT:

                    Helper.showWaitePaySound(SalesSignHelpActivity.this);
                    BillPaymentEntity entity= (BillPaymentEntity) msg.obj;

                    ScanOff();
                    final BaseDialog filterDialog=new BaseDialog(SalesSignHelpActivity.this);
                    filterDialog.setTitles("此单号【" + entity.getBillNo() + "】为代收货款单号，代收金额为：【￥"+Double.valueOf(entity.getBillPayment())+"】。请注意代收！");
                    filterDialog.show();
                    filterDialog.getvCanncel().setVisibility(View.GONE);
                    filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            filterDialog.dismiss();
                            ScanOpen();
                        }
                    });
                    break;
            }

            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sto_sales_sign_help);
        Bundle extras = getIntent().getExtras();
        title = extras.getInt("title");
        this.setTitleBottom(title, HomeBroadAction.SALES_MAN_BROAD);

        initWidget();
        initListen();
        initScanListener();
        initPointLayout(true);
        dataBusiness = new DataBusinessEntity();
        dataBusiness.initInsertData();
        initScanRecordAdapter(EnumTableNames.STATUS_TABLE_SALESMAN_HELP_SIGN);
        initScanRecordAdapter(EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //处理默认数据
        saveSalesNamesSP();
        adapter=new SalesSignSelectSpninerAdapter(this,names);
        namesSpinner.setAdapter(adapter);
    }

    /**
     * 初始化控件
     */
    private void initWidget() {
        code = (StoHhmEditText) this.findViewById(R.id.sign_odd_numbers_text);
        phoneET= (EditText) findViewById(R.id.et_phone);
        namesSpinner= (Spinner) findViewById(R.id.spinner_names);

        addUploadTable(EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);
        //这里要添加短信数据库插入
        addUploadTable(EnumTableNames.STATUS_TABLE_SALESMAN_HELP_SIGN);
    }

    /**
     * 监听控件
     */
    private void initListen() {

        namesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                signName= (String) names.get(pos);
                //Toast.makeText(SalesSignHelpActivity.this, "你点击的是:"+signName, Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });

        code.setEditDelete(new StoHhmEditText.EditClickListener() {

            @Override
            public void onEditDelete() {
                phoneET.requestFocus();
            }

            @Override
            public void onEditClickListener(View v) {
                if (code.getText().toString().length() == 0) {
                    Helper.showSoundToast(SalesSignHelpActivity.this,
                            getString(R.string.code_empty), false);
                } else {
                    onScanResults(code.getText().toString());
                }
            }
        });
        phoneET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Helper.isMobileNO(phoneET.getText().toString())) {
                    code.requestFocus();
                } else {
                    Helper.showSoundToast(SalesSignHelpActivity.this, "号码不正确!", false);
                    phoneET.setText("");
                    phoneET.requestFocus();
                }
            }
        });

        for (EditText editListener : edit) {
            /*
             * 监听EditText控件焦点切换
			 */
            editListener.setOnFocusChangeListener(new View.OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (hasFocus) {

                    }
                }
            });

			/*
             * 监听EditText内容个数
			 */
            editListener.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start,
                                          int before, int count) {

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start,
                                              int count, int after) {
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

        }

    }

    /**
     * 扫描数据处理
     */
    @SuppressLint("NewApi")
    private void processScanData() {
        try {

            if ( signName== null
                    || signName.length() == 0) {
                Helper.showSoundToast(this, "签名不能为空!", false);
                return;
            }
            if (Chineselength(signName) > 14) {
                Helper.showSoundToast(this, "签名过长,请减少签名长度!", false);
                return;
            }
            if (!isChineseChar(signName)) {
                Helper.showSoundToast(this, "签名不能包含非法字符!", false);
                return;
            }

            if (!Helper.isMobileNO(phoneET.getText().toString())) {
                Helper.showSoundToast(this, "号码不正确!", false);
                phoneET.setText("");
                phoneET.requestFocus();
                return;
            }

            if (!code.getText().toString().isEmpty()
                    && !(signName.isEmpty())// &&
                // (signName.equals(autograph.getText().toString()))
                    ) {

                //Add by wj过滤单号
                boolean isFilter= BillFilterUtil.isFilter(code.getText().toString().trim(),this);
                if(isFilter){
                    showFilterDialog(code.getText().toString().trim());
                    return;
                }
                //End by wj

                //代收货款校验
                int onOff=StoFilePreference.getInstance(this).getPayMentOnOff();
                if(1==onOff){
                    String bill=code.getText().toString().trim();
                    if("11".equals(bill.substring(0,2)) || "33".equals(bill.substring(0,2))){
                        new HelpGetPaymentThread(bill,SalesSignHelpActivity.this,mHandler).start();
                    }
                }
                //代收货款校验

                if (addPieceRecord()) {
                    //这里是添加短信
                    addHelpSignSmsPiece();
                    this.addCodeNumber();
                    setSaveData(true);

                    Helper.showSoundAndVibrator(this, true);
                    addScanRecordInfo(code.getText().toString(), dataBusiness.getWeight());
                    phoneET.setText("");
                    code.setSelection(code.length());
                    phoneET.requestFocus();
                }
                // 提示插入数据失败
                else {
                    Helper.showSoundToast(this,
                            getString(R.string.code_repeat), false);
                }
                ScanOpen();
            } else if (code.getText().toString().isEmpty()) {
                // 提示单号不能为空

            } else if (signName.isEmpty()) {
                // 提示签名不能为空
                SoundManager.getInstance(this).playFailureSound();
                Helper.showToast(SalesSignHelpActivity.this, "签名不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionLog.writeLog("processScanData", e.getMessage());
        }
    }

    /**
     * 添加签收短信的数据插入
     */
    private void addHelpSignSmsPiece() {
        DataBusinessEntity entity = new DataBusinessEntity();
        entity.initInsertData();
        entity.setBar_code_number(code.getText().toString());
        // 签收人
        entity.setRecv_person(signName);
        // 网点编号
        entity.setNet_code(StoFilePreference.getInstance(this)
                .getSiteCode());
        // 工号
        entity.setJob_number(StoFilePreference.getInstance(this)
                .getUserCode());
        entity.setSend_person(StoFilePreference.getInstance(this).getUserName());
        entity.setSend_phone(phoneET.getText().toString());
        StoDataBaseOperation.getInstance(this).insert(entity, EnumTableNames.STATUS_TABLE_SALESMAN_HELP_SIGN);
        this.addCodeNumber();
    }

    /**
     * 数据保存
     *
     * @return true/成功 or false/失败
     */
    private boolean addPieceRecord() {
        boolean ret;

        dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_SALESMAN_SIGN
                .getOpCode());
        dataBusiness.setBar_code_number(code.getText().toString());

        dataBusiness.setCodeType(getExpType(code.getText().toString()));
        // 签收人
        dataBusiness.setRecv_person(signName);
        // 网点编号
        dataBusiness.setNet_code(StoFilePreference.getInstance(this)
                .getSiteCode());
        // 工号
        dataBusiness.setJob_number(StoFilePreference.getInstance(this)
                .getUserCode());
        dataBusiness.setDifferent_flag("1");
        ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
                EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);
        return ret;
    }


    /**
     * 扫描码判断
     *
     * @param code 扫描码
     * @return true/ok or false
     */
    private boolean CheckScanCode(String code) {
        boolean ret = false;

        EnumScanCode status = ProcessScanCode.getInstance(this).ScanCodeResolve(
                code, EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);

        switch (status) {
            // 条码空
            case CODE_EMPTY:
                // Helper.showSoundToast(
                // SalesSignContentActivity.this,
                // getString(R.string.code_empty), false);
                break;
            // 非法条码
            case CODE_ILLEGAL:
                Helper.showSoundToast(SalesSignHelpActivity.this,
                        getString(R.string.error_code), false);
                break;
            // 成功条码
            case CODE_WAY_BILL:

                ret = true;
                break;
            default:
                break;
        }

        return ret;
    }

    /**
     * 非法符号判断(只能字母,数字,中文)
     *
     * @param content
     * @return
     */
    private boolean isChineseChar(String content) {
        Pattern p = Pattern.compile("^[\\w\\u4e00-\\u9fa5]+$");
        Matcher m = p.matcher(content);
        return m.matches();
    }

    private int Chineselength(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < value.length(); i++) {
            /* 获取一个字符 */
            String temp = value.substring(i, i + 1);
			/* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
				/* 中文字符长度为2 */
                valueLength += 2;
            } else {
				/* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

    /**
     * 保存默认的签收人
     */
    private void saveSalesNamesSP(){

        List<String> strs=StoFilePreference.getInstance(this).getSignNames();

        if(null==strs){
            names.add(getText(R.string.select_item_1).toString());
            names.add(getText(R.string.select_item_2).toString());
            names.add(getText(R.string.select_item_3).toString());
            names.add(getText(R.string.select_item_4).toString());

            StoFilePreference.getInstance(this).setSignNames(names);
        }else {
            names=strs;
        }

    }

    /**
     * 其他按钮点击事件
     * @param view
     */
    public void selectSignNamesClick(View view){

        Intent intent=new Intent(this,SalesSignHelpSelectNames.class);
        startActivity(intent);
    }

    /**
     * 扫描结果回调
     * @param scanData
     */
    @Override
    protected void handlerScanData(String scanData) {

        if (scanData != null && !scanData.equals("")) {
            String result = scanData;
            code.setText("");
            code.setText(result);
            code.setSelection(code.length());

            if (CheckScanCode(result)) {
                processScanData();
            }
            code.setText("");
        }
    }

    @Override
    public void onBackPressed() {
        showNotice();
    }

    @Override
    protected void onDestroy() {
        edit.clear();
        super.onDestroy();
    }
}
